package com.scalar.chiptrack.sales.actions.quote;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.quote.QuotationDAO;
import com.scalar.chiptrack.sales.forms.quote.QuoteSearchForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Basha
 * @version
 */

public final class SearchQuotationAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/salesQuotations.do";


    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {

        QuoteSearchForm subform = ( QuoteSearchForm ) form;
        String action           = request.getParameter ( "action" );
        String isSampleStr      = request.getParameter ( "isSample" );
        ArrayList ordersList = new ArrayList ();
        String viewExpired = request.getParameter ( "viewExpired" );
        if ( viewExpired == null )
        {
            request.setAttribute ( "viewExpired", "NO" );
        }
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }

        HashMap errors = new HashMap ();
        if ( action == null )
        {
            request.setAttribute ( "showList", "FALSE" );
        }

        int isSample = 1; //default set to salesOrder
        if ( isSampleStr != null && isSampleStr.length () != 0 )
        {
            try
            {
                isSample = Integer.parseInt ( isSampleStr );
            }
            catch ( NumberFormatException ignore ) { isSample = 1; }
        }

        if ( "SearchQuotation".equals ( action ) )
        {
            if ( user.isActionAllowed ( Functionality.SALES_CHANGE_ORDER, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }

            String customerId = ( String ) BeanUtils.getSimpleProperty ( form, "customerId" );
            String manufacturingPartNo = request.getParameter ( "manufacturingPartNo" );
            String quotationId = ( String ) BeanUtils.getSimpleProperty ( form, "quotationId" );
            String customerPO = ( String ) BeanUtils.getSimpleProperty ( form, "customerPO" );
            String endUser =  ( String ) BeanUtils.getSimpleProperty ( form, "endUser" );
            //String status = ( String ) BeanUtils.getSimpleProperty ( form, "status" );
            String fromDate = ( String ) BeanUtils.getSimpleProperty ( form, "fromDate" );
            String toDate = ( String ) BeanUtils.getSimpleProperty ( form, "toDate" );

            ordersList = QuotationDAO.loadQuotationsToChange ( quotationId, customerId, manufacturingPartNo, viewExpired, user.getUserId(), customerPO, endUser, fromDate, toDate );

            if ( ordersList.size () == 0 )
            {
                errors.put ( ERROR_CHANGE_QUOTATION_NOT_FOUND, null );
                request.setAttribute ( "showList", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showList", "TRUE" );
            }

            if ( viewExpired == null )
            {
                request.setAttribute ( "viewExpired", "NO" );
            }
            else
            {
                request.setAttribute ( "viewExpired", "YES" );
            }
        }

        if ( "changeSearchQuotation".equals ( action ) )
        {
            request.setAttribute ( "showList", "FALSE" );
            request.setAttribute ( "quoteSearchForm", null );
        }

        request.setAttribute ( "customerList", CustomerDAO.getAllCustomerNamesByUserTypeByCustomerType ( null, user, isSample ) );
        request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
        request.setAttribute ( "endUserList", CustomerDAO.loadAllEndUserNames( null, 1 ) );
        request.setAttribute ( "ordersList", ordersList );

        if ( !errors.isEmpty () )
        {
            request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        }

        return ( mapping.findForward ( "success" ) );

    }

    public static ArrayList loadManufacturingProducts( int isSample ) throws Exception
    {
        ArrayList parts = new ArrayList ();
        Iterator list   = null;
        if( isSample == 0 )
        {
            list = FinishedGoodsDAO.loadFinishedGoods().iterator ();
        }
        else
        {
            list = FinishedGoodsDAO.loadAllFinishedGoods().iterator ();
        }

        parts.add ( new org.apache.struts.util.LabelValueBean ( "All Products", "" ) );
        while ( list.hasNext () )
        {
            FinishedGoods product = ( FinishedGoods ) list.next ();
            parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), product.getManufacturingPartNo () ) );
        }
        return parts;
    }

}
